package com.ruoyi.functiontest.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.functiontest.mapper.TollBridgeStatTestMapper;
import com.ruoyi.functiontest.domain.TollBridgeStatTest;
import com.ruoyi.functiontest.service.ITollBridgeStatTestService;
import com.ruoyi.function.domain.TollBridgeStat;
import com.ruoyi.function.service.ITollBridgeStatService;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * 收费桥梁统计测试Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@Service
public class TollBridgeStatTestServiceImpl implements ITollBridgeStatTestService 
{
    @Autowired
    private TollBridgeStatTestMapper tollBridgeStatTestMapper;

    @Autowired
    private ITollBridgeStatService tollBridgeStatService;

    /**
     * 查询收费桥梁统计测试
     * 
     * @param id 收费桥梁统计测试主键
     * @return 收费桥梁统计测试
     */
    @Override
    public TollBridgeStatTest selectTollBridgeStatTestById(Long id)
    {
        return tollBridgeStatTestMapper.selectTollBridgeStatTestById(id);
    }

    /**
     * 查询收费桥梁统计测试列表
     * 
     * @param tollBridgeStatTest 收费桥梁统计测试
     * @return 收费桥梁统计测试
     */
    @Override
    public List<TollBridgeStatTest> selectTollBridgeStatTestList(TollBridgeStatTest tollBridgeStatTest)
    {
        return tollBridgeStatTestMapper.selectTollBridgeStatTestList(tollBridgeStatTest);
    }

    /**
     * 新增收费桥梁统计测试
     * 
     * @param tollBridgeStatTest 收费桥梁统计测试
     * @return 结果
     */
    @Override
    public int insertTollBridgeStatTest(TollBridgeStatTest tollBridgeStatTest)
    {
        return tollBridgeStatTestMapper.insertTollBridgeStatTest(tollBridgeStatTest);
    }

    /**
     * 修改收费桥梁统计测试
     * 
     * @param tollBridgeStatTest 收费桥梁统计测试
     * @return 结果
     */
    @Override
    public int updateTollBridgeStatTest(TollBridgeStatTest tollBridgeStatTest)
    {
        return tollBridgeStatTestMapper.updateTollBridgeStatTest(tollBridgeStatTest);
    }

    /**
     * 批量删除收费桥梁统计测试
     * 
     * @param ids 需要删除的收费桥梁统计测试主键
     * @return 结果
     */
    @Override
    public int deleteTollBridgeStatTestByIds(Long[] ids)
    {
        return tollBridgeStatTestMapper.deleteTollBridgeStatTestByIds(ids);
    }

    /**
     * 删除收费桥梁统计测试信息
     * 
     * @param id 收费桥梁统计测试主键
     * @return 结果
     */
    @Override
    public int deleteTollBridgeStatTestById(Long id)
    {
        return tollBridgeStatTestMapper.deleteTollBridgeStatTestById(id);
    }
    
    /**
     * 根据ID查询是否有子节点
     * 
     * @param id 节点ID
     * @return 结果
     */
    @Override
    public boolean hasChildById(Long id)
    {
        return tollBridgeStatTestMapper.hasChildById(id) > 0;
    }

    /**
     * 批量更新实测单位审核状态（review1字段设置为0）
     * 
     * @return 结果
     */
    @Override
    public int updateReview1ToZero()
    {
        return tollBridgeStatTestMapper.updateReview1ToZero();
    }

    /**
     * 检查所有记录的review1字段是否为0
     * 
     * @return 结果
     */
    @Override
    public boolean checkAllReview1IsZero()
    {
        return tollBridgeStatTestMapper.countReview1NotZero() == 0;
    }

    /**
     * 根据条件批量更新业主审核状态（review2字段设置为0）
     * 
     * @param tollBridgeStatTest 查询条件
     * @return 结果
     */
    @Override
    public int updateReview2ToZeroByCondition(TollBridgeStatTest tollBridgeStatTest)
    {
        return tollBridgeStatTestMapper.updateReview2ToZeroByCondition(tollBridgeStatTest);
    }

    /**
     * 检查所有记录的review1和review2字段是否都为0
     * 
     * @return 结果
     */
    @Override
    public boolean checkAllReview1AndReview2AreZero()
    {
        return tollBridgeStatTestMapper.countReview1OrReview2NotZero() == 0;
    }

    /**
     * 批量更新中心审核状态（review3字段设置为0）
     * 
     * @return 结果
     */
    @Override
    public int updateReview3ToZero()
    {
        return tollBridgeStatTestMapper.updateReview3ToZero();
    }

    /**
     * 导入收费桥梁统计测试数据
     * 简化导入逻辑：直接按照Excel原始格式导入，通过id和parentid来确定数据
     * 
     * @param tollBridgeStatTestList 收费桥梁统计测试列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importTollBridgeStatTest(List<TollBridgeStatTest> tollBridgeStatTestList, Boolean isUpdateSupport)
    {
        if (tollBridgeStatTestList == null || tollBridgeStatTestList.isEmpty())
        {
            return "导入数据不能为空！";
        }
        
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        // 简化导入逻辑：直接按照Excel原始格式导入
        for (TollBridgeStatTest data : tollBridgeStatTestList)
        {
            try
            {
                // 基本数据验证
                if (data.getRoadName() == null) {
                    data.setRoadName("");
                }
                if (data.getNodeName() == null) {
                    data.setNodeName("");
                }
                
                // 通过id和parentid来确定数据
                TollBridgeStatTest existingNode = null;
                
                // 使用通过id和parentid组合来精确匹配数据
                TollBridgeStatTest query = new TollBridgeStatTest();
                query.setId(data.getId());
                query.setParentId(data.getParentId());
                
                List<TollBridgeStatTest> existingNodes = tollBridgeStatTestMapper.selectTollBridgeStatTestByIdAndParentId(query);
                if (existingNodes != null && !existingNodes.isEmpty()) {
                    existingNode = existingNodes.get(0);
                }
                
                if (existingNode != null) {
                    // 已存在节点，如果支持更新则更新
                    if (isUpdateSupport) {
                        existingNode.setRoadName(data.getRoadName());
                        existingNode.setNodeName(data.getNodeName());
                        existingNode.setLeftLength(data.getLeftLength());
                        existingNode.setRightLength(data.getRightLength());
                        existingNode.setAvgLength(data.getAvgLength());
                        existingNode.setRemark(data.getRemark());
                        existingNode.setParentId(data.getParentId());
                        
                        tollBridgeStatTestMapper.updateTollBridgeStatTest(existingNode);
                        successNum++;
                    } else {
                        // 不支持更新，跳过此条数据
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + ". 数据已存在，跳过: " + data.getRoadName() + "-" + data.getNodeName());
                    }
                } else {
                    // 不存在节点，创建新节点
                    TollBridgeStatTest newNode = new TollBridgeStatTest();
                    newNode.setId(data.getId()); // 使用Excel中的id值
                    newNode.setRoadName(data.getRoadName());
                    newNode.setNodeName(data.getNodeName());
                    newNode.setLeftLength(data.getLeftLength());
                    newNode.setRightLength(data.getRightLength());
                    newNode.setAvgLength(data.getAvgLength());
                    newNode.setRemark(data.getRemark());
                    newNode.setParentId(data.getParentId());
                    
                    tollBridgeStatTestMapper.insertTollBridgeStatTest(newNode);
                    successNum++;
                }
                
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + ". 导入失败：";
                if (data.getRoadName() != null)
                {
                    msg += "路段名称：" + data.getRoadName();
                }
                if (data.getNodeName() != null)
                {
                    msg += "，桥梁名称：" + data.getNodeName();
                }
                failureMsg.append(msg + e.getMessage());
            }
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new RuntimeException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();
    }

    /**
     * 检查所有数据的review1、review2和review3是否为0，并将数据同步到正式表
     * 
     * @return 同步结果信息
     */
    @Override
    @Transactional
    public String syncDataToTollBridgeStat()
    {
        // 1. 检查所有数据的review1、review2和review3是否都为0
        int count = tollBridgeStatTestMapper.countReview1OrReview2OrReview3NotZero();
        if (count > 0) {
            throw new RuntimeException("存在未完成审核的数据，请确保所有数据的review1、review2和review3字段都为0");
        }
        
        // 2. 查询所有审核通过的数据
        TollBridgeStatTest query = new TollBridgeStatTest();
        List<TollBridgeStatTest> testDataList = tollBridgeStatTestMapper.selectTollBridgeStatTestList(query);
        
        if (testDataList == null || testDataList.isEmpty()) {
            return "同步失败：没有找到可同步的数据";
        }
        
        int successNum = 0;
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        
        // 3. 遍历数据，同步到正式表
        for (TollBridgeStatTest testData : testDataList) {
            try {
                // 创建正式表对象
                TollBridgeStat tollBridgeStat = new TollBridgeStat();
                tollBridgeStat.setId(testData.getId());
                tollBridgeStat.setParentId(testData.getParentId());
                tollBridgeStat.setRoadName(testData.getRoadName());
                tollBridgeStat.setNodeName(testData.getNodeName());
                tollBridgeStat.setLeftLength(testData.getLeftLength());
                tollBridgeStat.setRightLength(testData.getRightLength());
                tollBridgeStat.setAvgLength(testData.getAvgLength());
                tollBridgeStat.setRemark(testData.getRemark());
                
                // 检查正式表中是否已存在相同id的数据
                TollBridgeStat existingData = tollBridgeStatService.selectTollBridgeStatById(testData.getId());
                
                if (existingData != null) {
                    // 已存在，更新数据
                    tollBridgeStatService.updateTollBridgeStat(tollBridgeStat);
                } else {
                    // 不存在，插入数据
                    tollBridgeStatService.insertTollBridgeStat(tollBridgeStat);
                }
                
                successNum++;
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + ". 同步失败：";
                if (testData.getRoadName() != null) {
                    msg += "路段名称：" + testData.getRoadName();
                }
                if (testData.getNodeName() != null) {
                    msg += "，桥梁名称：" + testData.getNodeName();
                }
                failureMsg.append(msg + "，错误：" + e.getMessage());
            }
        }
        
        if (failureNum > 0) {
            failureMsg.insert(0, "同步完成，但部分数据同步失败！成功同步 " + successNum + " 条，失败 " + failureNum + " 条，错误如下：");
            return failureMsg.toString();
        } else {
            return "恭喜您，数据同步成功！共同步 " + successNum + " 条数据到正式表。";
        }
    }
}
